{# templates/pay.html #}
{% extends "base.html" %}

{% block title %}Pay Order {{ order.order_no or ('#' ~ order.id) }}{% endblock %}

{% block content %}
<div class="max-w-xl mx-auto py-8">
  <h1 class="text-2xl font-semibold mb-4">
    Pay Order {{ order.order_no or ('#' ~ order.id) }}
  </h1>

  <div class="bg-white shadow rounded-lg p-4 mb-6">
    <p class="text-sm text-gray-500 mb-2">Amount Due</p>
    <p class="text-2xl font-bold">
      {{ '%.2f'|format(display_amount) }} {{ currency }}
    </p>
  </div>

  <div id="paypal-button-container"></div>
</div>

{# PayPal SDK + 集成逻辑 #}
<script src="https://www.paypal.com/sdk/js?client-id={{ paypal_client_id }}&currency={{ currency }}"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
    paypal.Buttons({
      // 1) 创建 PayPal 订单：调用我们自己的后端 /api/paypal/create-order
      createOrder: function (data, actions) {
        return fetch("{{ url_for('paypal.paypal_create_order') }}", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": "{{ csrf_token() }}",
          },
          body: JSON.stringify({ order_id: {{ order.id }} })
        }).then(function (res) {
          return res.json();
        }).then(function (data) {
          if (data.error) {
            alert("Create order error: " + data.error);
            throw new Error(data.error);
          }
          return data.orderID;  // PayPal 的 orderID
        });
      },

      // 2) 客户在 PayPal 页面完成支付后，前端调用我们的 /api/paypal/capture
      onApprove: function (data, actions) {
        return fetch("{{ url_for('paypal.paypal_capture') }}", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-CSRFToken": "{{ csrf_token() }}",
          },
          body: JSON.stringify({
            order_id: {{ order.id }},
            orderID: data.orderID
          })
        }).then(function (res) {
          return res.json();
        }).then(function (data) {
          if (data.error) {
            alert("Capture error: " + data.error);
            throw new Error(data.error);
          }
          // 支付成功，跳转到订单详情页
          window.location.href = "{{ url_for('shop.order_detail', order_no='__ORDER_NO__') }}".replace(
            "__ORDER_NO__", data.order_no
          );
        });
      },

      onError: function (err) {
        console.error(err);
        alert("PayPal error: " + err);
      }
    }).render('#paypal-button-container');
  });
</script>
{% endblock %}